package com.android.clinic.app;

import android.content.Context;
import android.os.Environment;
import android.support.multidex.MultiDex;
import android.support.multidex.MultiDexApplication;
import com.android.clinic.app.entity.UserInfo;
import com.android.clinic.app.utils.ACache;
import com.android.clinic.app.utils.LocalDataUtils;
import com.jiongbull.jlog.JLog;
import io.agora.AgoraAPIOnlySignal;
import io.agora.rtc.IRtcEngineEventHandler;
import io.agora.rtc.RtcEngine;

/**
 * Created by cheng on 2018/1/26.
 */
public class ClinicApplication extends MultiDexApplication {

    private AgoraAPIOnlySignal mAngoraAPI;
    public RtcEngine mRtcEngine;
    private OnAngoraEngineInterface onAngoraEngineInterface;
    private String appId = "";

    public static String cacheDir;
    public static UserInfo userInfo = null;

    public ACache mACache;

    private static volatile ClinicApplication mApplication;

    public static ClinicApplication getInstance() {
        if (mApplication == null) {
            synchronized (ClinicApplication.class) {
                if (mApplication == null) {
                    mApplication = new ClinicApplication();
                }
            }
        }
        return mApplication;
    }

    public void setOnAngoraEngineInterface(OnAngoraEngineInterface onAngoraEngineInterface) {
        this.onAngoraEngineInterface = onAngoraEngineInterface;
    }

    public AgoraAPIOnlySignal getAngoraAPI() {
        return mAngoraAPI;
    }

    public RtcEngine getRtcEngine() {
        return mRtcEngine;
    }

    public String getAppId() {
        return appId;
    }

    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(base);
        MultiDex.install(this);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mApplication = this;
        appId = "8ac5df6ec1374a1787400a2386c40589";
        mACache = ACache.getInstances(mApplication);
        JLog.init(this).setDebug(BuildConfig.DEBUG);
        setupAngoraEngine();

        /**如果存在SD卡则将缓存写入SD卡,否则写入手机内存*/
        if (null != getApplicationContext().getExternalCacheDir() && existSDCard()) {
            cacheDir = getApplicationContext().getExternalCacheDir().toString();
        } else {
            cacheDir = getApplicationContext().getCacheDir().toString();
        }
    }

    public static UserInfo getUserInfo() {
        if (null == ClinicApplication.userInfo) {
            ClinicApplication.userInfo = (UserInfo) LocalDataUtils.loadDataFromLocate(ClinicApplication.getInstance(),
                    UserInfo.class.getSimpleName());
        }
        return ClinicApplication.userInfo;
    }

    public static void saveUserInfo(UserInfo userInfo) {
        ClinicApplication.userInfo = userInfo;
        if (userInfo != null) {
            LocalDataUtils.saveDataToLocate(ClinicApplication.getInstance(), UserInfo.class.getSimpleName(), userInfo);
        }else{
            ClinicApplication.getInstance().deleteFile(UserInfo.class.getSimpleName());
        }
    }

    /**
     * 判断是否有SD卡
     * @return
     */
    private boolean existSDCard() {
        return android.os.Environment.getExternalStorageDirectory().equals(Environment.MEDIA_MOUNTED);
    }

    private void setupAngoraEngine() {
        try {
            mAngoraAPI = AgoraAPIOnlySignal.getInstance(this, appId);
            mRtcEngine = RtcEngine.create(this, appId , mRtcEventHandler);
            JLog.e("setupAngoraEngine mRtcEngine :" + mRtcEngine);
            if (mRtcEngine != null) {
                mRtcEngine.setLogFile("/sdcard/sdklog.txt");
            }

        } catch (Exception e) {
            JLog.e(e.toString());
            throw new RuntimeException("NEED TO check rtc sdk init fatal error\n" + e.toString());
        }
    }

    private final IRtcEngineEventHandler mRtcEventHandler = new IRtcEngineEventHandler() {

        @Override
        public void onFirstRemoteVideoDecoded(int uid, int width, int height, int elapsed) {
            if (onAngoraEngineInterface != null){
                onAngoraEngineInterface.onFirstRemoteVideoDecoded(uid, width, height, elapsed);
            }
        }

        @Override
        public void onUserOffline(int uid, int reason) {
            if (onAngoraEngineInterface != null){
                onAngoraEngineInterface.onUserOffline(uid ,reason);
            }
        }

        @Override
        public void onUserMuteVideo(int uid, boolean muted) {
            if (onAngoraEngineInterface != null){
                onAngoraEngineInterface.onUserMuteVideo(uid, muted);
            }
        }

        @Override
        public void onJoinChannelSuccess(String channel, int uid, int elapsed) {
            super.onJoinChannelSuccess(channel, uid, elapsed);
            if (onAngoraEngineInterface != null){
                onAngoraEngineInterface.onJoinChannelSuccess(channel, uid, elapsed);
            }
        }
    };

    public interface OnAngoraEngineInterface{

        /**
         * 远端视频接收解码会回调
         * @param uid      用户ID
         * @param width    视频流宽(像素)
         * @param height   视频流高(像素)
         * @param elapsed  加入频道开始到该回到触发的延迟(毫秒)
         */
        void onFirstRemoteVideoDecoded(final int uid, int width, int height, int elapsed);


        /**
         * 去他用户离开当前频道回调
         * @param uid     用户ID
         * @param reason  离线原因: USER_OFFLINE_QUIT(0): 用户主动离开; USER_OFFLINE_DROPPED(1): 因过长时间收不到对方数据包，超时掉线
         */
        void onUserOffline(int uid, int reason) ;

        /**
         * 其他用户已停发/已重发视频流回调
         * @param uid   用户ID
         * @param muted true: 该用户已暂停发送视频流; false: 该用户已恢复发送视频流
         */
        void onUserMuteVideo(final int uid, final boolean muted);

        /**
         * 加入频道回调
         * @param channel
         * @param uid
         * @param elapsed
         */
        void onJoinChannelSuccess(String channel, int uid, int elapsed);

    }
}
